from wtforms import StringField, IntegerField
from wtforms.validators import ValidationError, Length, DataRequired
from app.common.enums import PublishType
from app.form.base_form import BaseForm
from app.models import Category


class ArticleForm(BaseForm):
    """添加文章表单验证
    """
    title = StringField(validators=[
        DataRequired('文章标题不允许为空'),
        Length(1, 255, message="文章标题1~255个字符")
    ])
    content = StringField(validators=[DataRequired('文章内容不允许为空')])
    has_type = StringField(validators=[DataRequired('文章状态不允许为空')])
    category_id = IntegerField(validators=[DataRequired('分类不允许为空')])

    # 判断文章状态
    def validate_has_type(self, field):
        type_dict = PublishType._value2member_map_
        if int(field.data) not in type_dict:
            raise ValidationError(message="文章状态不存在")

    # 判断分类是否存在
    def validate_category_id(self, field):
        category_id = int(field.data)
        category = Category.query.get(category_id)
        if category is None:
            raise ValidationError(message="文章分类不存在")
